package com.chr.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.chr.constant.Constant;
import com.chr.entity.Order;
import com.chr.entity.User;
import com.chr.service.OrderService;
import com.chr.service.UserService;
import com.chr.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chr.properties.AlipayProperties;
import com.chr.util.DateUtil;

/**
 * 支付宝支付Controller
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController {
	

	@Resource
	private AlipayProperties alipayProperties;

	@Autowired
	private OrderService orderService;

	@Autowired
	private UserService userService;

	private final static Logger logger= LoggerFactory.getLogger(AlipayController.class);


	/**
	 * 支付请求
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/pay")
	public void pay(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws ServletException, Exception{

		    User currentUser=(User)session.getAttribute("currentUser");


		    // 判断用户是否登录
			if(currentUser==null){
				response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
				response.getWriter().print("<html><body><script type='text/javascript'>alert('大佬，请您先登录下哈！');history.back(-1);</script></body></html>");
				response.getWriter().close();
				return;
			}
		    logger.info(currentUser.getOpenid()+" 用户发起支付请求，IP:"+request.getRemoteHost());
			ServletContext application = request.getServletContext();
			Map<String,String> propertyMap = (HashMap)application.getAttribute("propertyMap"); //  支付总金额
			String totalAmount=propertyMap.get("k10");

			Order order=new Order();

			String orderNo=DateUtil.getCurrentDateStr(); // 生成订单号
			
			// String totalAmount="0.01"; // 支付总金额
			String subject="VIP会员购买"; // 订单名称
			String body="VIP购买"; // 商品描述

			
			String form=""; // 生成支付表单

		    order.setOrderNo(orderNo);
		    order.setPay(false);
		    order.setSubject(subject);
		    order.setTotalAmount(totalAmount);
		    order.setWay("支付宝");
		    order.setUser(currentUser);

			// 封装请求客户端
			AlipayClient client=new DefaultAlipayClient(alipayProperties.getUrl(), alipayProperties.getAppid(), alipayProperties.getRsa_private_key(), alipayProperties.getFormat(), alipayProperties.getCharset(), alipayProperties.getAlipay_public_key(), alipayProperties.getSigntype());
			

			// 支付请求
			AlipayTradePagePayRequest alipayRequest=new AlipayTradePagePayRequest();
			alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
			alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());
			AlipayTradePayModel model=new AlipayTradePayModel();
			model.setProductCode("FAST_INSTANT_TRADE_PAY"); // 设置销售产品码
			model.setOutTradeNo(orderNo); // 设置订单号
			model.setSubject(subject); // 订单名称
			// model.setTotalAmount("0.01"); // 支付总金额
			model.setTotalAmount(totalAmount); // 支付总金额
			model.setBody(body); // 设置商品描述
			alipayRequest.setBizModel(model);

			form=client.pageExecute(alipayRequest).getBody(); // 生成表单

			orderService.add(order);

			response.setContentType("text/html;charset=" + alipayProperties.getCharset()); 
			response.getWriter().write(form); // 直接将完整的表单html输出到页面 
			response.getWriter().flush(); 
			response.getWriter().close();
	}
	
	/**
	 * 支付宝服务器同步通知页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/returnUrl")
	public ModelAndView returnUrl(HttpServletRequest request)throws Exception{
		logger.info("支付宝服务器同步通知进入");
		ModelAndView mav=new ModelAndView();
		mav.addObject("title", "同步通知地址_Java知识分享网");
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
			System.out.println("name:"+name+",valueStr:"+valueStr);
		}
		
		boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSigntype()); //调用SDK验证签名

		//——请在这里编写您的程序（以下代码仅作参考）——
		if(signVerified) {
			logger.info("支付宝服务器同步-验证成功！");
			mav.addObject("success", true);
		}else {
			logger.info("支付宝服务器同步-验证失败！");
			mav.addObject("success", false);
		}
		mav.setViewName("returnUrl");
		return mav;
	}

    /**
     * 支付宝服务器异步通知
     * @param request
     * @return
     */
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request)throws Exception{
         logger.info("支付宝服务器异步通知进入");
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            System.out.println("name:"+name+",valueStr:"+valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSigntype()); //调用SDK验证签名
        //商户订单号
        String out_trade_no = request.getParameter("out_trade_no");
        //交易状态
        String trade_status = request.getParameter("trade_status");

        if(signVerified){ // 验证成功 更新订单信息
			logger.info(out_trade_no+"：支付宝服务器异步验证成功！");
            if(trade_status.equals("TRADE_FINISHED")){
               logger.info(out_trade_no+"：TRADE_FINISHED");
            }
            if(trade_status.equals("TRADE_SUCCESS")){
               logger.info(out_trade_no+"TRADE_SUCCESS");
            }
            if(StringUtil.isNotEmpty(out_trade_no)){
                Order order=orderService.findById(out_trade_no); // 获取订单
                if(order!=null){

                	// 修改订单状态
                    order.setBuyTime(new Date()); // 支付时间
                    order.setPay(true); // 设置支付状态已经支付
                    orderService.update(order);

					logger.info(out_trade_no+"：支付宝服务器异步修改订单状态成功！");

                    // 修改用户会员等级
					User user=order.getUser();
					user.setLevel(Constant.LEVEL_VIP);
					userService.update(user);

					logger.info(out_trade_no+"：支付宝服务器异步修改会员等级成功！");
                }
            }
        }else{
			logger.info(out_trade_no+"：支付宝服务器异步验证失败！");
        }
    }


}
